//
//  MTSearchClubResultViewController.swift
//  MT
//
//  Created by ooops on 2020/5/17.
//  Copyright © 2020 张强. All rights reserved.
//

import UIKit
import MTCategory
import YPNavigationBarTransition
import RxSwift
import RxCocoa

extension MTSearchClubResultViewController: UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return result.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: MTClubRichListViewCell.reuseIdentity(), for: indexPath) as! MTClubRichListViewCell
        configureCell(cell: cell, forRowAt: indexPath)
        return cell
    }
    
    func configureCell(cell: MTClubRichListViewCell, forRowAt indexPath: IndexPath) {
        let model = self.result[indexPath.row]
        model.number = indexPath.row
//        if let gid = model.pushId {
//        }
        
        cell.model = model
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 64
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let model = self.result[indexPath.row]
        guard let clubName = model.pushId else { return }
        
        JMSGGroup.groupInfo(withGroupId: "\(clubName)", completionHandler: { [weak self] (result, error) in
            guard let weakSelf = self else { return }
            if error == nil, let group = result as? JMSGGroup {
                DispatchQueue.main.async {
                    
                    let clubDetail = MTNewClubDetailViewController(group: group, model: model)
                    
                    weakSelf.navigationController?.pushViewController(clubDetail, animated: true)
                }
            }
        })
    }
    
}

class MTSearchClubResultViewController: BaseViewController {
    
    private lazy var provider: MTProvider<MTClubApi> = {
        let provider = MTProvider<MTClubApi>(plugins: [MTLoadingDataPlugin.init(viewController: self)])
        return provider
    }()
    
    private var result: [MTClubRichListResultModel] = []

    var searchController: SKSearchController!
    /// 用户手机号 / 觅颜号
    var userMTorPhoneNumber: String = ""
    /// 搜索时 选中的俱乐部
    private var selectedIndex: Int = 0
    
    convenience init(selectedIndex: Int) {
        self.init()
        self.selectedIndex = selectedIndex
    }
    
    lazy var tableView: UITableView = {
        let table = UITableView(frame: self.view.bounds, style: .plain)
        table.delegate = self
        table.dataSource = self
        table.register(MTClubRichListViewCell.self, forCellReuseIdentifier: MTClubRichListViewCell.reuseIdentity())
        table.separatorStyle = .none
        table.tableFooterView = UIView()
        table.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 220, right: 0)
        table.isHidden = true
        return table
    }()
    
    // MARK: - 加载数据
    /// - Parameter loadMore: 是否加载更多
    private func loadData() {
        let queryParam: [String : Any] = ["search" : self.userMTorPhoneNumber]
        
        if selectedIndex == 0 {
            MTClubTool.queryRich(provider: provider, requestParam: queryParam, complete: { [weak self] (model) in
                
                guard let weakSelf = self else { return }
                weakSelf.comporseData(model: model)
                
            }) { [weak self] (error) in
                guard let weakSelf = self else { return }
            }
        } else {
            MTClubTool.queryLester(provider: provider, requestParam: queryParam, complete: { [weak self] (model) in
                
                guard let weakSelf = self else { return }
                weakSelf.comporseData(model: model)
                
            }) { [weak self] (error) in
                guard let weakSelf = self else { return }
            }
        }
    }
    
    private func comporseData(model: MTClubRichListModel?) {
        weak var weakSelf = self
        if let m = model {
            debugPrint("message: ", m.message ?? "")
            if let r = m.result {
                if r.count == 0 {
                    DispatchQueue.main.async {
                        MBProgressHUD_JChat.show(text: "未搜索到俱乐部信息", view: weakSelf!.view, 2)
                        weakSelf?.updateUI(minHeight: false)
                    }
                    return
                }
                weakSelf?.result = r
                weakSelf?.updateUI(minHeight: true)
            }
            
            DispatchQueue.main.async {
                weakSelf?.tableView.reloadData()
            }
        }
    }
    
    private func updateUI(minHeight: Bool) {
        searchButton.snp.updateConstraints { (make) in
            make.height.equalTo(minHeight ? 0 : 84)
        }
        searchButton.isHidden = minHeight
    }
    
    lazy var searchButton: MTSearchFriendListHeaderView = {
        let s = MTSearchFriendListHeaderView()
        s.isHidden = true
        s.delegate = self
        return s
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.addSubview(searchButton)
        view.addSubview(tableView)
        
        searchButton.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalToSuperview().offset(StatusBarHeight + NavigationBarHeight + 10)
            make.height.equalTo(84)
        }
        
        tableView.snp.makeConstraints { (make) in
            //make.edges.equalToSuperview()
            make.bottom.left.right.equalToSuperview()
            make.top.equalTo(searchButton.snp.bottom)
        }

        searchController = SKSearchController(searchResultsController: nil)
        if #available(iOS 11.0, *) {
            navigationItem.searchController = searchController
            navigationItem.hidesSearchBarWhenScrolling = false // 这样子可以在进入页面的时候不隐藏
            searchController.obscuresBackgroundDuringPresentation = false
            searchController.hidesNavigationBarDuringPresentation = true // 编辑的时候隐藏导航栏
        } else {
            tableView.tableHeaderView = searchController.searchBar
        }
        
        setupSearchController()
        //getFriendList()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        setupSearchController()
    }
    
    /// 构建搜索控制器
    func setupSearchController() {
        searchController.placeholder = "输入俱乐部名称"
        searchController.customizeCancelButton = { button in
            button.setAttributedTitle(NSAttributedString(string: "取消", attributes: [.foregroundColor : UIColor.text.x1d1a1a, .font: PingFangSCMediumFont(14)]), for: .normal)
            //button.backgroundColor = UIColor(hex: 0xEE7F79)
            //button.layer.cornerRadius = 4
            //button.setTitleColor(.red, for: .normal)
        }
        
        //searchController.leftIcon = UIImage(named: "football")
        //searchController.leftIconColor =  UIColor.text.x1d1a1a
        //searchController.setRightBookmarkIcon(image: UIImage(named: "speaker"), color: UIColor(hex: 0xEE7F79), for: [.normal])
        searchController.setRightClearIcon(image: UIImage(named: "x"), color: UIColor(hex: 0xcdcdcd), for: [.normal])
        
        searchController.cursorColor = UIColor(hex: 0x333333)
        searchController.textFieldTextColor = UIColor.text.x9b9b9b
        searchController.textFieldFont = PingFangSCMediumFont(14)
        searchController.hideBorderLines = true
        searchController.textFieldBackgroundColor = UIColor(hex: 0xFFFFFF)
        
        searchController.textFieldBorderColor = UIColor(hex: 0xe6e6e6).cgColor
        searchController.textFieldBorderWidth = 1
        searchController.textFieldCornerRadius = 4
        searchController.removeBgView()
        
        searchController.searchTextDidChange = { [weak self] searchBar, text in
            //debugPrint("Keyword: \(text)")
            guard let weakSelf = self else { return }
            weakSelf.userMTorPhoneNumber = text
            
            weakSelf.searchButton.isHidden = text == "" ? true : false
            weakSelf.tableView.isHidden = text == "" ? true : false
            DispatchQueue.main.async {
                weakSelf.searchButton.snp.updateConstraints { (make) in
                    make.height.equalTo(text == "" ? 0 : 64)
                }
            }
            
            /// 筛选好友列表
            if text != "" {
                //userFriendList.count
                DispatchQueue.main.async {
                    weakSelf.searchButton.snp.updateConstraints { (make) in
                        make.height.equalTo(84)
                    }
                    weakSelf.searchButton.isHidden = false
                }
            } else {
                weakSelf.result.removeAll()
                DispatchQueue.main.async {
                    weakSelf.tableView.reloadData()
                }
            }
            
            weakSelf.searchButton.setSearchTitlt(title: text)
        }
        
        searchController.searchButtonClickHandler = { [weak self] searchBar in
            guard let weakSelf = self else { return }
            weakSelf.loadData()
        }
        
        searchController.searchBarCancelButtonClickHandler = { searchBar in
            self.navigationController?.dismiss(animated: true, completion: nil)
            self.navigationController?.popViewController(animated: true)
        }
        
        DispatchQueue.main.async {
            self.searchController.searchBar.becomeFirstResponder()
            if #available(iOS 13.0, *) {
                self.searchController.searchBar.searchTextField.becomeFirstResponder()
            } else {
                // Fallback on earlier versions
            }
        }
    }
}

/// 搜索IM好友列表业务
extension MTSearchClubResultViewController {
    /// 获取好友列表
    private func getFriendList() {
        
        
    }
    
}


extension MTSearchClubResultViewController {
    
    override func yp_navigtionBarConfiguration() -> YPNavigationBarConfigurations {
        return [.backgroundStyleColor, .backgroundStyleOpaque, .showShadowImage]
    }
}

extension MTSearchClubResultViewController: MTSearchFriendListHeaderViewDelegate {
    func didTapSearchFriendButton() {
        loadData()
    }
}
